package vip.zhy.faststart.framework.jwt;

import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.Objects;

@Slf4j
public class Jwt {

    public final static ThreadLocal<String> USER_ID = new ThreadLocal<>();

    private final static String USER_KEY = "userId";

    private final static String START = "Bearer ";

    private final static long time = 30 * 24 * 60 * 60 * 1000L;

    private final static String signature = "DZKqTLk5X7NE1NshxCE3YC3tXouiQ5i";

    public static String create(String userId) {
        return START + Jwts.builder()
                .claim(USER_KEY, userId)
                .setExpiration(new Date(System.currentTimeMillis() + time))
                .signWith(SignatureAlgorithm.HS256, signature)
                .compact();
    }

    public static boolean parseToken(String token) {
        if (Objects.isNull(token)) {
            log.info("Objects.isNull(token) = true");
            return false;
        }
        token = token.replace(START, "");
        Jws<Claims> claimsJws;
        try {
            claimsJws = Jwts.parser()
                    .setSigningKey(signature)
                    .parseClaimsJws(token);
        } catch (SignatureException e) {
            log.error("token error", e);
            return false;
        }
        // Jws<Claims> = header={alg=HS256},body={userId=xxxxdddd, exp=1664521238},signature=NIecANdeTUPa6fii_W_2vC0-j9XnCtEa1InTjI4dyKo
        log.info("token = {}, Jws<Claims> = {}", token, claimsJws);
        Claims body = claimsJws.getBody();
        String userId = body.get(USER_KEY, String.class);
        USER_ID.set(userId);
        return true;
    }

//    public static void main(String[] args) {
//        System.out.println(create("xxxxdddd"));
//        parseToken("eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiJ4eHh4ZGRkZCIsImV4cCI6MTY2NDUyMTIzOH0.NIecANdeTUPa6fii_W_2vC0-j9XnCtEa1InTjI4dyKo");
//    }

}
